<template>
	<view class="wrap">
		<view class="content">
			<view class="info-btn">
				<view class="info-btn-left" @click="submit" v-if="isCanvas">
					<view class="info-btn-left-text">
						确认
					</view>
				</view>
				<view class="info-btn-left info-btn-left-a" v-else>
					<view class="info-btn-left-text">
						确认
					</view>
				</view>
				<view class="info-btn-right" @click="signatureEvent">
					<view class="info-btn-left-right">
						清除
					</view>
				</view>
			</view>
			<view class="info-form">
				<canvas canvas-id="firstCanvas" id="firstCanvas" @touchstart.stop="touchstartEvent($event)"
					@touchmove.stop="touchmoveEvent($event)" @touchend.stop="touchendEvent($event)"
					style="width: 100%; height: 100%" disable-scroll="false"></canvas>
				<view class="info-form-text">
					签写本人姓名<text>(需横着签字)</text>
				</view>
			</view>
			<view>
				<canvas canvas-id="camCacnvs"
					:style="{'position':'absolute','top':'-2000%','width':canvasWidth+'px','height':canvasHeight+'px','background':'transparent'}"></canvas>
					
			</view>
		</view>
	</view>
</template>
<script>
	import {
		Agreement
	} from '@/api/new_api.js';

	import {
		TOKENNAME,
		HTTP_REQUEST_URL
	} from '@/config/app.js'
	
	import store from '@/store';
	export default {

		data() {
			return {
				isCanvas:false,
				canvas:'',
				canvasWidth:559,
				canvasHeight:300,
				context:null,
				clientYTop:0,
				touch:0,
				
				fileList1:[],
				
				timerId:null,
				isSubmit:true,
				imgUrls:'',
			}
		},
		onLoad() {
			this.initCanvas();
		},
		onShow() {

		},
		methods: {
			/**
			 * 初始化Canvas
			 */
			initCanvas() {
				let that = this;
				const contextInit = uni.createCanvasContext("firstCanvas");
				contextInit.setFillStyle("rgba(255, 255, 255, 0)");
				contextInit.fillRect(0, 0, 500, 350);
				that.context = contextInit;
				contextInit.draw();
			},
			/**
			 * 重新签字事件
			 */
			signatureEvent() {
				if (!this.isSubmit) return
				this.initCanvas();
				this.clear();
				this.isCanvas = false;
			},
			/**
			 * 清空Canvas
			 */
			clear() {
				this.touch = 0;
				this.context.draw();
				this.context.setFillStyle("rgba(255, 255, 255, 0)");
				this.context.fillRect(0, 0, 500, 180);
			},
			//小程序(开发者工具，手机打开小程序，app，有轻微差别，所以取了e.changedTouches[0].x  ||e.changedTouches[0].clientX）
			/**
			 * Canvas开始滑动
			 */
			touchstartEvent(e) {
				let that = this;
				that.isCanvas = true;
				that.touch += 1;
				var query = uni.createSelectorQuery();
				query.select("#firstCanvas").boundingClientRect();
				query.selectViewport().scrollOffset();
				query.exec(function(res) {
					that.clientYTop = res[0].top;
					var x = e.changedTouches[0].x || e.changedTouches[0].clientX
					var y = e.changedTouches[0].y || (e.changedTouches[0].clientY - that.clientYTop)
					that.context.moveTo(
						x,
						y
					);
				});
			},
			/**
			 * 滑动事件
			 */
			touchmoveEvent(e) {
				let that = this;
				console.log('222222222222222222222');
				that.isCanvas = true;
				if (that.clientYTop) {
					var x = e.changedTouches[0].x || e.changedTouches[0].clientX
					var y = e.changedTouches[0].y || (e.changedTouches[0].clientY - that.clientYTop)
					that.context.lineTo(
						x,
						y
					);
					that.context.stroke();
					that.context.draw(true);
					that.context.moveTo(
						x,
						y
					);
				}
			},
			/**
			 * 移开清除 clientYTop
			 */
			touchendEvent() {
				this.clientYTop = 0;
			},
			
			/**
			 * Canvas导出图片
			 */
			exportFilePath() {
				return new Promise((resolve, reject) => {
					this.context.draw(
						true,
						setTimeout(() => {
							uni.canvasToTempFilePath({
								fileType: "png",
								canvasId: "firstCanvas",
								success: (res) => resolve(res.tempFilePath),
								fail: () => ($ajax.showToast("导出失败"), reject()),
							})
						}, 900)
					);
				});
			},
			
			submit() {
				let that = this;
				if (that.isSubmit) {
					that.isSubmit = false
				} else {
					return
				}
				if (!that.isCanvas) return uni.$u.toast('请签写本人姓名！')
				clearTimeout(that.timerId)
				that.timerId = setTimeout(() => {
					uni.showLoading({
						title: '提交中...'
					})
					setTimeout(async () => {
						const filePath = await that.exportFilePath();
						// svaeSignImg(filePath);
						// imgUrls.value = filePath;
						// getUpload();
						that.rotateAndSaveImage(filePath)
						uni.hideLoading()
					}, 100)
				}, 600)
			},
			
			rotateAndSaveImage(tempFilePath) {
				let that = this;
				uni.getImageInfo({
					src: tempFilePath,
					success: (imageInfo) => {
						const imagePath = imageInfo.path;
						    const imageWidth = imageInfo.width;
						    const imageHeight = imageInfo.height;
						const ctx = uni.createCanvasContext('camCacnvs');
							const canvasWidth = 559; // 旋转90度后，宽度变为原图的高度
							const canvasHeight = 300; // 旋转90度后，高度变为原图的宽度
						    // 第三步：在Canvas上旋转图片
						    ctx.clearRect(0, 0, canvasWidth, canvasHeight);
						    ctx.save();
						    ctx.translate(canvasWidth / 2, canvasHeight / 2);
						    ctx.rotate(-Math.PI / 2);
						    ctx.drawImage(imagePath, -canvasHeight / 2, -canvasWidth / 2, canvasHeight, canvasWidth);
						    ctx.restore();
						
						ctx.draw(true, () => {
						  // 4. 获取旋转后的图片数据
						  uni.canvasToTempFilePath({
						    canvasId: 'camCacnvs',
						    success: (canvasRes) => {
						      const rotatedTempFilePath = canvasRes.tempFilePath;
							  console.log(rotatedTempFilePath,'----00099')
							  that.imgUrls = rotatedTempFilePath;
							  that.getUpload();
						    },
						    fail: (err) => {
						      console.error('获取旋转后图片数据失败', err);
						      uni.showToast({
						        title: '获取旋转后图片数据失败',
						        icon: 'error'
						      });
						    }
						  });
						});
					}
				})
			},
			
			
			svaeSignImg(url) {
				let that = this;
				let tempFilePaths = url;
				that.canvas = uni.createCanvasContext('camCacnvs');
				uni.getImageInfo({ // 获取图片的信息
					src: tempFilePaths,
					success: (msg) => {
						that.canvas.fillStyle = 'transparent';
						that.canvas.fillRect(0, 0, that.canvasWidth, that.canvasHeight);
						// 逆时针旋转90度
						that.canvas.translate(that.canvasWidth / 2, that.canvasHeight / 2)
						that.canvas.rotate(270 * Math.PI / 180)
						// that.canvas.drawImage(msg.path, -4*width/5, -height/2, height, width);
						that.canvas.setGlobalAlpha(1);
						//如果你修改了画布后不能完全展示出来，可以调整这下面四个参数
						//因为翻转了，所以分别是 靠上，靠左，高，宽，慢慢修改，不然很容易就超出界面了，然而以为没显示出来
						that.canvas.drawImage(msg.path, -that.canvasWidth * 0.25, -that.canvasHeight * 0.9,
							that.canvasWidth * 0.5, that.canvasHeight * 1.8)
						that.canvas.draw(false, () => {
							setTimeout(() => {
								uni.canvasToTempFilePath({
									canvasId: 'camCacnvs',
									destWidth: that.canvasWidth,
									destHeight: that.canvasHeight,
									fileType: 'png',
									quality: 1, //图片质量
									success(vas) {
										uni.showLoading()
										console.log('完成', vas.tempFilePath);
										setTimeout(() => {
											imgUrls.value = vas.tempFilePath;
											that.getUpload();
											uni.hideLoading()
										}, 1000)
									},
									fail(err) {
										console.log(err)
									}
								})
							}, 300)
			
						})
			
					}
				})
			},
			
			getUpload(){
				let that = this;
				console.log('resres------------1111');
				that.uploadImageOne("file",
					(res) => {
						console.log(res,'resres------------');
						that.getAgreement(res.data.url)
					}
				);
			},
			
			getAgreement(url) {
				let that = this;
				that.isSubmit = true;
				uni.showLoading({
					title: '提交中...'
				})
				Agreement({
					seal_img: url
				}).then((res) => {
					uni.hideLoading()
					uni.$u.toast(res.msg)
					console.log(res,'------------resres');
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/index/index'
						})
					}, 900)
				}).catch((error) => {
					uni.hideLoading()
					// uni.showModal({
					// 	content: error.msg,
					// 	showCancel: false,
					// 	confirmColor: '我知道了',
					// 	success(res) {
					// 		if (res.confirm) {
					// 			uni.navigateBack();
					// 		}
					// 	}
					// })
					console.log('error', error, '----------------');
				})
			},
			
			uploadImageOne(inputName, successCallback, errorCallback){
				let that = this;
				uni.showLoading({
					title: '图片上传中',
				});
				let urlPath = HTTP_REQUEST_URL + '/api/upload/image'
				let localPath = that.imgUrls;
				uni.uploadFile({
					url: urlPath,
					filePath: localPath,
					name: inputName,
					formData: {
						'filename': inputName
					},
					header: {
						// #ifdef MP
						"Content-Type": "multipart/form-data",
						// #endif
						[TOKENNAME]: 'Bearer ' + store.state.app.token
					},
					success: function(res) {
						console.log(res)
						
						uni.hideLoading();
						if (res.statusCode == 403) {
							that.Tips({
								title: res.data
							});
						} else {
							let data = res.data ? JSON.parse(res.data) : {};
							
							console.log('error', data, '----------------');
							
							if (data.status == 200) {
								successCallback && successCallback(data)
							} else {
								errorCallback && errorCallback(data);
								that.Tips({
									title: data.msg
								});
							}
						}
					},
					fail: function(res) {
						uni.hideLoading();
						uni.showToast({
							title: '上传图片失败',
							icon: "none"
						});
					}
				})
			},
			
			
		
			
			
		}
	}
</script>
<style lang="scss" scoped>
	.wrap {
		width: 750rpx;
		min-height: 100vh;
		padding-top: 32rpx;
		box-sizing: border-box;
		background: #f8f8fa;

		.content {
			display: flex;
			justify-content: space-between;
			padding: 0 26rpx 0 34rpx;

			.info-btn {

				.info-btn-left {
					width: 72rpx;
					height: 216rpx;
					border-radius: 32rpx;
					background: linear-gradient(223.69deg, rgba(255, 250, 207, 1) 0%, rgba(244, 222, 129, 1) 100%);
					display: flex;
					align-items: center;
					justify-content: center;

					.info-btn-left-text {
						transform: rotate(90deg);
						font-size: 32rpx;
						font-weight: 400;
						color: rgba(128, 72, 28, 1);
					}
				}

				.info-btn-left-a {
					background: #ddd !important;
				}

				.info-btn-right {
					margin-top: 32rpx;
					width: 72rpx;
					height: 216rpx;
					border-radius: 32rpx;
					border: 1px solid rgba(128, 72, 28, 1);
					display: flex;
					align-items: center;
					justify-content: center;

					.info-btn-left-right {
						transform: rotate(90deg);
						font-size: 32rpx;
						font-weight: 400;
						color: rgba(128, 72, 28, 1);
					}
				}
			}

			.info-form {
				width: 600rpx;
				height: 1118rpx;
				background: rgba(255, 255, 255, 1);
				position: relative;

				.info-form-text {
					position: absolute;
					right: -150rpx;
					top: 200rpx;
					z-index: 9999;
					transform: rotate(90deg);
					font-size: 32rpx;
					font-weight: 400;
					color: rgba(61, 61, 61, 1);

					text {
						color: red;
					}
				}
			}
		}
	}
</style>